<template>
  <div>
    <el-card>
      <el-form :model="form" size="mini" label-position="top" ref="form">
        <el-row :gutter="10">
          <el-col :lg="5" :md="6">
            <el-form-item label="渠道名称" prop="CHANNELTYPE">
              <el-select v-model="form.CHANNELTYPE" size="mini" clearable placeholder="请选择渠道">
                <el-option v-for="item in channelOption" :key="item.FIELDKEY" :label="item.FIELDVALUE"
                  :value="item.FIELDKEY"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg='8' :md='12' class="searchBtnMarginTop">
            <el-button type="primary" icon="el-icon-search" @click="queryRules" size='mini'>查询</el-button>
            <el-button type="warning" size="mini" icon="el-icon-refresh" @click="resetForm('form')">重置</el-button>
            <el-button type="primary" size="mini" @click="openEditDialog('','add')" icon="el-icon-plus">新增规则</el-button>
          </el-col>
        </el-row>
      </el-form>
      <el-table :data="tableData" :row-key="getRowKeys" :expand-row-keys="expands" style="width: 100%;margin-top:10px;"
        :row-class-name="tableRowClassName">
        <el-table-column prop="CLASSESINFO" type="expand">
          <template slot-scope="scope">
            <el-table width="60%" :data="scope.row.RSPSTRUCT" :header-cell-style="tableHeaderStyle"
              :row-class-name="eventRowClassName">
              <el-table-column prop="ID" label="ID"></el-table-column>
              <el-table-column prop="MATCHNO" label="过滤条件编号"></el-table-column>
              <el-table-column prop="MATCH" label="过滤条件"></el-table-column>
              <el-table-column prop="MATCHNAME" label="过滤条件名"></el-table-column>
              <el-table-column prop="WEIGHT" label="权重"></el-table-column>
              <el-table-column prop="REMARK1" label="备注"></el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <!-- <el-table-column type="index" label="序号" width="50">
        </el-table-column> -->
        <el-table-column prop="CHANNELTYPE" label="渠道类型" width="120">
        </el-table-column>
        <el-table-column prop="CHANNELNAME" label="渠道名称" align="center">
        </el-table-column>
        <el-table-column prop="MAXNUM" label="最大笔数" align="center">
        </el-table-column>
        <el-table-column prop="MINNUM" label="最小笔数">
        </el-table-column>
        <el-table-column label="操作" align="center" width="260">
          <template slot-scope="scope">
            <el-button type="warning" size="mini" @click="openEditDialog(scope.row,'update')">修改</el-button>
            <el-button type="danger" size="mini" @click="delRules(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <component :is="dialogList.editDialog" :option="editOptions" @refreshTable="queryRules"></component>

    </el-card>
  </div>
</template>
<script>
  import request from "@/common/utils/requestQC";
  import getGlobalParams from "@/common/utils/getGlobalParams";
  import ruleQuery from '@/message/QCManage/sampleManage/autoSampleRules/autoSampleRulesQuery';
  import ruleManage from '@/message/QCManage/sampleManage/autoSampleRules/autoSampleRulesManage';
  import dictionary from '@/message/wfm/baseData/dictionaryManage/dictionaryQuery'
  import requestWFM from "@/common/utils/requestWFM";
  import editDialog from "./dialog/editDialog";
  import queyData from "@/message/QCManage/sampleManage/sampleDictionary/sampleDictionaryQuery";


  export default {
    data() {
      return {
        dictionaryOption: [],
        dialogList: {
          editDialog
        },
        channelOption: [],
        expands: [],
        getRowKeys(row) {
          return row.CHANNELTYPE;
        },
        popoverShow: false,
        tableTotal: 1,
        currpage: 1,
        pageSize: getGlobalParams.get("PageSize"),
        form: { //表单数据
          CHANNELTYPE: '',
        },
        tableData: [],
        editOptions: {
          isShow: false,
          title: '',
          flag: '',
        },
      }
    },
    created() {},
    mounted() {
      this.queryRules()
      this.channelQuery()
      this.queryRuleDictionary()
    },
    filters: {},
    methods: {
      // 查询规则字典
      async queryRuleDictionary() {
        let resBody = new queyData()
        resBody.data.PageFlag = '4'
        resBody.data.CurrPage = '1'
        resBody.data.PageRowNum = '200'
        let response = await request(resBody);
        if (response.SYS_HEAD.ReturnCode == "000000") {
          this.dictionaryOption = response.BODY.struct
        } else {
          this.$message({
            type: "error",
            message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
          })
        }
      },
      //打开修改新增Dialog
      async openEditDialog(row, flag) {
        this.editOptions.channelOption = this.channelOption
        this.editOptions.dictionaryOption = this.dictionaryOption
        this.editOptions.flag = flag
        if (flag == 'add') {
          this.editOptions.isShow = true
          this.editOptions.title = '新增抽样规则'
        } else {
          let data = []
          row.RSPSTRUCT.forEach(item => {
            data.push(this.findID(item))
          })
          let id = []
          data.forEach(item=>{
            id.push(item.ID)
          })
          this.editOptions.tableData = data
          this.editOptions.ID = id
          this.editOptions.isShow = true
          this.editOptions.title = '修改抽样规则'
          this.editOptions.row = row
        }
      },
      findID(row) {
        let data = {}
        this.dictionaryOption.forEach(item => {
          if (item.COLUMNID == row.MATCHNO && item.ROLELEVEL == row.MATCH && item.ROLELEVELNAME == row.MATCHNAME) {
            data = item
            data.WEIGHT = row.WEIGHT
            data.REMARK1 = row.REMARK1
          }
        })
        return data
      },
      // 查询业务渠道
      async channelQuery() {
        let resBody = new dictionary();
        resBody.data.FIELDCODE = 'CHANNELTYPE'
        resBody.data.CurrPage = 1
        resBody.data.PageRowNum = 100
        let response = await requestWFM(resBody);
        if (response.SYS_HEAD.ReturnCode == "000000") {
          this.channelOption = response.BODY.FIEDATA;
        } else {
          this.$message({
            type: "error",
            message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
          })
        }
      },
      eventRowClassName(
        row,
        rowIndex
      ) {
        // console.log(row.row.EVENT.length)
        // return 'background-color: #f0f9eb !important;'
        return 'success-row'
      },
      tableHeaderStyle({
        row,
        column,
        rowIndex,
        columnIndex
      }) {
        return 'background-color:#C1E0B8;'
      },
      tableRowClassName(
        row,
        rowIndex
      ) {
        return row.row.RSPSTRUCT.length == 0 ? 'expand' : '';
      },
      OTINFOFormatter(row, column) {
        let array = []
        row.OTINFO.forEach(item => {
          array.push(item.OTNAME)
        });
        return array.join(',')
      },
      resetForm(formName) { //重置查询表单
        this.$refs["" + formName].resetFields();
        // this.checkedIds = [];
      },
      compare(property) {
        return function (a, b) {
          var value1 = a[property];
          var value2 = b[property];
          return value1 - value2;
        }
      },
      // 多笔规则查询
      async queryRules() {
        let resBody = new ruleQuery()
        resBody.data.CHANNELTYPE = this.form.CHANNELTYPE
        let response = await request(resBody);
        if (response.SYS_HEAD.ReturnCode == "000000") {
          this.tableData = response.BODY.RSPSTRUCT
          // 把源数据先变成目标数据的规则
          var oldDataRule = []
          this.tableData.forEach(el => {
            var oldObj = {
              CHANNELTYPE: el.CHANNELTYPE,
              CHANNELNAME: el.CHANNELNAME,
              MAXNUM: el.MAXNUM,
              MINNUM: el.MINNUM,
              RSPSTRUCT: []
            }
            var struct = {
              ID:el.ID,
              MATCHNO: el.MATCHNO,
              MATCHNAME: el.MATCHNAME,
              MATCH: el.MATCH,
              WEIGHT: el.WEIGHT,
              REMARK1: el.REMARK1,
            }
            oldObj.RSPSTRUCT.push(struct)
            oldDataRule.push(oldObj)
          })

          /**
           * 先去重，后合并
           * 1、源数据去重
           * 2、把去重后的数据和源数据中相同name的数据合并citys
           */
          var newData = []
          var newObj = {}
          oldDataRule.forEach((el, i) => {
            if (!newObj[el.CHANNELTYPE]) {
              newData.push(el);
              newObj[el.CHANNELTYPE] = true;
            } else {
              newData.forEach(el => {
                if (el.CHANNELTYPE === oldDataRule[i].CHANNELTYPE) {
                  el.RSPSTRUCT = el.RSPSTRUCT.concat(oldDataRule[i].RSPSTRUCT);
                  // el.citys = [...el.citys, ...oldDataRule[i].citys]; // es6语法
                }
              })
            }
          })
          this.tableData = newData
          this.tableData.forEach(item => {
            if (item.RSPSTRUCT.length > 0) {
              this.expands.push(item.CHANNELTYPE)
            }
          })
        } else {
          this.$message({
            type: "error",
            message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
          })
        }
      },
      // 删除规则
      delRules(row) {
        this.$confirm('此操作将删除该规则, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          let resBody = new ruleManage()
          resBody.data.OPERATE = 'D'
          resBody.data.CHANNELTYPE = row.CHANNELTYPE
          let response = await request(resBody);
          if (response.SYS_HEAD.ReturnCode == "000000") {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.queryRules()
          } else {
            this.$message({
              type: "error",
              message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
            })
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        })
      },
      eventRowworkName(
        row,
        rowIndex
      ) {
        return 'success-row'
      },
      tableHeaderStyle({
        row,
        column,
        rowIndex,
        columnIndex
      }) {
        return 'background-color:#C1E0B8;'
      }
    },
  }

</script>
<style lang="scss">
  .expand .el-table__expand-column .cell {
    display: none;
  }

  .el-table .warning-row {
    background: #e4e1e1;
  }

  .el-table .success-row {
    background: #f0f9eb;
  }

</style>
<style lang="scss" scoped>
</style>
